package com.neusoft.neuiotms.dcam.common.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.common.dto.LocationDTO;
import com.neusoft.neuiotms.dcam.common.model.Location;
import com.neusoft.neuiotms.dcam.common.repository.LocationRepository;

@Component
public class LocationConverter extends AbstractConverter<Location, LocationDTO> {

    @Autowired
    private LocationRepository locationRepository;

    @Override
    public Location toModel(final LocationDTO dto) {
        Location model;
        if (dto.isNew()) {
            model = new Location();
        } else {
            model = this.locationRepository.getOne(dto.getId());
        }

        if ((dto.getParentId() != null) && (dto.getParentId() != -1)) {
            model.setParent(this.locationRepository.getOne(dto.getParentId()));
        }
        if (dto.getParentCode() != null) {
            model.setParent(this.locationRepository.findByCode(dto.getParentCode()));
        }

        model.setName(dto.getName());
        model.setCode(dto.getCode());
        model.setSort(dto.getSort());
        return model;
    }

    @Override
    public LocationDTO toDTO(final Location model, final boolean forListView) {
        final LocationDTO dto = new LocationDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());

        if (null != model.getParent()) {
            dto.setParentId(model.getParent().getId());
            dto.setParentCode(model.getParent().getCode());
            dto.setParentName(model.getParent().getName());
        }
        return dto;
    }

}
